import { memo, useState } from "react";
import { LockOutlined, MobileOutlined } from "@ant-design/icons";
import { LoginFormPage, ProFormCaptcha, ProFormCheckbox, ProFormText } from "@ant-design/pro-components";
import { message, Tabs } from "antd";
import LoginStyle from "./style";
import { sendAuthCode_service } from "../../graphql/auth_code/inedx";
import { useMutation } from "@apollo/client";
import { login_service } from "../../graphql/login";
import { AUTH_TOKEN } from "../../constant";
import { useNavigate } from "react-router-dom";

type LoginType = "phone";

const Login = memo(() => {
  const [loginType, setLoginType] = useState<LoginType>("phone");
  const [fetch_sendAuthCode_service] = useMutation(sendAuthCode_service);
  const [fetch_login_service] = useMutation(login_service);

  const nav = useNavigate();

  // 点击发送验证码
  const sendAuthClick = async (tel: string) => {
    const data = await fetch_sendAuthCode_service({
      variables: {
        tel
      },
      fetchPolicy: "network-only"
    });
    if (!data) {
      await message.error("网络错误！请重试");
    }
    const resulet: { message: string; code: boolean } = data.data
      .sendAuthCode as {
      message: string;
      code: boolean;
    };
    if (resulet.code) {
      await message.success("获取验证码成功!");
    } else {
      await message.error(resulet.message);
    }
  };
  // 登录按钮点击
  const submitClick = async (value: Record<string, string>) => {
    const tel = value.mobile;
    const code = value.captcha;
    try {
      const data = await fetch_login_service({
        variables: {
          tel,
          code,
          isStudent: false
        }
      });
      const result = data.data.login as { message: string; data: string };
      if (result.message === "true") {
        if (value.autoLogin) {
          sessionStorage.setItem(AUTH_TOKEN, "");
          localStorage.setItem(AUTH_TOKEN, result.data);
        } else {
          localStorage.setItem(AUTH_TOKEN, "");
          sessionStorage.setItem(AUTH_TOKEN, result.data);
        }
        nav("/home/major");
        await message.success("登录成功!");
      } else {
        await message.error(result.message);
      }
    } catch (err) {
      await message.error("网络连接错误，请重试！");
    }
  };
  return (
    <LoginStyle>
      <div>
        <LoginFormPage
          backgroundImageUrl="https://danyun.oss-cn-chengdu.aliyuncs.com/DYE_login_bg.png"
          logo="https://danyun.oss-cn-chengdu.aliyuncs.com/brand.png"
          subTitle="让知识在云端飞翔，让未来更美好"
          onFinish={(value) => submitClick(value)}
        >
          <Tabs
            centered
            activeKey={loginType}
            onChange={(activeKey) => setLoginType(activeKey as LoginType)}
            items={[{ key: "phone", label: "手机号登录" }]}
          />
          {loginType === "phone" && (
            <>
              <ProFormText
                fieldProps={{
                  size: "large",
                  prefix: <MobileOutlined className={"prefixIcon"} />
                }}
                name="mobile"
                placeholder={"手机号"}
                rules={[
                  {
                    required: true,
                    message: "请输入手机号！"
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: "手机号格式错误！"
                  }
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined className={"prefixIcon"} />
                }}
                captchaProps={{
                  size: "large"
                }}
                placeholder={"请输入验证码"}
                captchaTextRender={(timing: boolean, count: number) => {
                  if (timing) {
                    return `${count} ${"获取验证码"}`;
                  }
                  return "获取验证码";
                }}
                phoneName="mobile"
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: "请输入验证码！"
                  }
                ]}
                onGetCaptcha={(tel: string) => sendAuthClick(tel)}
              />
            </>
          )}
          <div
            style={{
              marginBlockEnd: 24
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
          </div>
          <div className="filing-wrapper">
            <div>
              <a
                target="_blank"
                href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=51030202000185"
                className="public-security"
              >
                <img
                  src="https://danyun.oss-cn-chengdu.aliyuncs.com/filing-icon.png"
                  alt="图片加载失败"
                />
                <p>川公网安备 51030202000185号</p>
              </a>
            </div>
            <a className="filing" href="https://beian.miit.gov.cn">
              蜀ICP备2023023504号
            </a>
          </div>
        </LoginFormPage>
      </div>
    </LoginStyle>
  );
});

export default Login;
